<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>星际文件传输系统</title>
    <link rel="stylesheet" href="/styles.css?v=1.0">
    <script src="./modern-uploader.js?v=1.0"></script>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>星际文件传输系统</h1>
            <p class="subtitle">基于断点续传技术的高速文件传输</p>
        </div>
        
        <!-- 文件上传区域 -->
        <div class="upload-section">
            <h2>🚀 文件上传</h2>
            <div id="uploader" class="uploader">
                <div class="queueList">
                    <div id="dndArea" class="placeholder">
                        <div class="upload-icon">📁</div>
                        <div id="filePicker" class="file-picker-btn">选择文件</div>
                        <p class="drag-text">或将文件拖拽到此处</p>
                    </div>
                </div>
                <div class="statusBar" style="display:none;">
                    <div class="progress-container">
                        <div class="progress-bar">
                            <div class="progress-fill"></div>
                        </div>
                        <div class="progress-text">0%</div>
                    </div>
                    <div class="info"></div>
                    <div class="btns">
                        <div id="filePicker2" class="file-picker-btn secondary">继续添加</div>
                        <div class="uploadBtn sci-fi-btn">开始传输</div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 错误消息显示区域 -->
        <div id="errorMessage" class="error-message" style="display:none;"></div>
        
        <!-- 文件列表 -->
        <div class="download-section">
            <h2>💾 文件列表</h2>
            <div class="file-list-container">
                <p th:if="${fileList != null and fileList.empty}" class="no-files">暂无文件</p>
                <ul th:unless="${fileList == null or fileList.empty}" class="file-list">
                    <li th:each="file : ${fileList}" class="file-item">
                        <span th:if="${file.directory}" class="file-name folder" th:text="${file.name}" th:data-id="${file.id}" onclick="enterFolder(this)"></span>
                        <span th:unless="${file.directory}" class="file-name" th:text="${file.name}"></span>
                        <span th:if="${file.directory}" class="folder-icon">📁</span>
                        <a th:unless="${file.directory}" th:href="@{/download/{filename}(filename=${file.name})}" target="_blank" class="sci-fi-btn download-link">下载</a>
                    </li>
                </ul>
            </div>
        </div>
    </div>

    <script>
        // 路径历史记录，用于文件夹浏览
        let pathHistory = [''];
        let currentPathIndex = 0;
        
        document.addEventListener('DOMContentLoaded', function() {
            // 初始化现代化上传器
            const uploader = new ModernUploader({
                chunkSize: 2 * 1024 * 1024, // 2MB
                threads: 3
            });
            
            let currentFile = null;

            // 文件选择事件
            document.getElementById('filePicker').addEventListener('click', function() {
                const input = document.createElement('input');
                input.type = 'file';
                input.onchange = function(e) {
                    const file = e.target.files[0];
                    if (file) {
                        currentFile = file;
                        const chunkCount = uploader.selectFile(file);
                        document.querySelector('.statusBar').style.display = 'block';
                        document.querySelector('.info').textContent = `文件已选择: ${file.name} (${chunkCount} 个分片)`;
                    }
                };
                input.click();
            });

            // 拖拽上传事件
            const dndArea = document.getElementById('dndArea');
            dndArea.addEventListener('dragover', function(e) {
                e.preventDefault();
                dndArea.classList.add('dragover');
            });
            
            dndArea.addEventListener('dragleave', function(e) {
                e.preventDefault();
                dndArea.classList.remove('dragover');
            });
            
            dndArea.addEventListener('drop', function(e) {
                e.preventDefault();
                dndArea.classList.remove('dragover');
                const file = e.dataTransfer.files[0];
                if (file) {
                    currentFile = file;
                    const chunkCount = uploader.selectFile(file);
                    document.querySelector('.statusBar').style.display = 'block';
                    document.querySelector('.info').textContent = `文件已选择: ${file.name} (${chunkCount} 个分片)`;
                }
            });

            // 开始上传按钮点击事件
            document.querySelector('.uploadBtn').addEventListener('click', function() {
                if (!currentFile) {
                    document.querySelector('.info').textContent = '请先选择文件';
                    return;
                }

                uploader.startUpload(
                    // 进度回调
                    function(uploadedChunks, totalChunks) {
                        const percent = Math.round((uploadedChunks / totalChunks) * 100);
                        document.querySelector('.progress-fill').style.width = percent + '%';
                        document.querySelector('.progress-text').textContent = percent + '%';
                        document.querySelector('.info').textContent = `上传进度: ${uploadedChunks}/${totalChunks} (${percent}%)`;
                    },
                    // 完成回调
                    function() {
                        document.querySelector('.info').textContent = '传输成功';
                        // 刷新文件列表
                        setTimeout(function() {
                            location.reload();
                        }, 1000);
                    },
                    // 错误回调
                    function(error) {
                        document.querySelector('.info').textContent = '传输失败: ' + error;
                        console.error('上传错误:', error);
                    }
                );
            });

            function showError(message) {
                const errorDiv = document.getElementById('errorMessage');
                errorDiv.textContent = message;
                errorDiv.style.display = 'block';
                
                // 3秒后自动隐藏错误消息
                setTimeout(() => {
                    errorDiv.style.display = 'none';
                }, 3000);
            }
        });
        
        // 进入文件夹函数
        function enterFolder(element) {
            const folderId = element.getAttribute('data-id');
            // 更新路径历史记录
            pathHistory = pathHistory.slice(0, currentPathIndex + 1);
            pathHistory.push(folderId);
            currentPathIndex++;
            
            // 发送请求到服务器获取文件夹内容
            fetch('/folder/' + folderId)
                .then(response => {
                    // 检查响应是否成功
                    if (!response.ok) {
                        throw new Error(`HTTP error! status: ${response.status}`);
                    }
                    // 检查内容类型是否为JSON
                    const contentType = response.headers.get('content-type');
                    if (!contentType || !contentType.includes('application/json')) {
                        throw new Error('Received non-JSON response');
                    }
                    return response.json();
                })
                .then(data => {
                    // 更新文件列表
                    updateFileList(data, folderId);
                })
                .catch(error => {
                    console.error('获取文件夹内容失败:', error);
                    alert('获取文件夹内容失败: ' + error.message);
                });
        }
        
        // 返回上级目录函数
        function goToParentFolder() {
            if (currentPathIndex > 0) {
                currentPathIndex--;
                const parentId = pathHistory[currentPathIndex];
                
                if (parentId === '') {
                    // 返回根目录
                    location.reload();
                } else {
                    // 发送请求到服务器获取文件夹内容
                    fetch('/folder/' + parentId)
                        .then(response => {
                            // 检查响应是否成功
                            if (!response.ok) {
                                throw new Error(`HTTP error! status: ${response.status}`);
                            }
                            // 检查内容类型是否为JSON
                            const contentType = response.headers.get('content-type');
                            if (!contentType || !contentType.includes('application/json')) {
                                throw new Error('Received non-JSON response');
                            }
                            return response.json();
                        })
                        .then(data => {
                            // 更新文件列表
                            updateFileList(data, parentId);
                        })
                        .catch(error => {
                            console.error('获取文件夹内容失败:', error);
                            alert('获取文件夹内容失败: ' + error.message);
                        });
                }
            }
        }
        
        // 更新文件列表显示
        function updateFileList(fileList, currentFolderId = '') {
            const fileListContainer = document.querySelector('.file-list');
            if (!fileListContainer) return;
            
            // 清空现有内容
            fileListContainer.innerHTML = '';
            
            // 添加返回上级目录按钮（如果不是在根目录）
            if (currentPathIndex > 0) {
                const backButton = document.createElement('li');
                backButton.className = 'file-item';
                backButton.innerHTML = `
                    <span class="file-name folder" onclick="goToParentFolder()">..</span>
                    <span class="folder-icon">📁</span>
                `;
                fileListContainer.appendChild(backButton);
            }
            
            // 添加新内容
            if (fileList.length === 0) {
                const emptyMessage = document.createElement('li');
                emptyMessage.className = 'file-item';
                emptyMessage.innerHTML = '<p class="no-files">此文件夹为空</p>';
                fileListContainer.appendChild(emptyMessage);
                return;
            }
            
            fileList.forEach(file => {
                const li = document.createElement('li');
                li.className = 'file-item';
                
                if (file.directory) {
                    li.innerHTML = `
                        <span class="file-name folder" data-id="${file.id}" onclick="enterFolder(this)">${file.name}</span>
                        <span class="folder-icon">📁</span>
                    `;
                } else {
                    li.innerHTML = `
                        <span class="file-name">${file.name}</span>
                        <a href="/download/${encodeURIComponent(file.name)}" target="_blank" class="sci-fi-btn download-link">下载</a>
                    `;
                }
                
                fileListContainer.appendChild(li);
            });
        }
    </script>
</body>
</html>